<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '编辑地址',
  },
}
</route>

<script lang="ts" setup>
//
import { reactive, ref, onMounted } from 'vue'
// 地址
import { useColPickerData } from '@/hooks/useColPickerData'
import { getAddress, updateAddress, addAddress } from '@/service/user/address'
import { CustomAddressVo } from '@/service/user/address.d'
const { colPickerData, findChildrenByCode } = useColPickerData()
const model = reactive<CustomAddressVo>({
  id: null,
  customId: null,
  name: '',
  phone: '',
  isDefault: 0,
  tagName: null,
  address: '',
  provinceCode: '',
  cityCode: '',
  districtCode: '',
  fullAddress: '',
  provinceName: '',
  cityName: '',
  districtName: '',
})

const form = ref()
let timer = null
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        console.log(model, 'model')
        if (model.provinceCode === '' || model.cityCode === '' || model.districtCode === '') {
          uni.showToast({
            title: '请选择地址',
            icon: 'none',
          })
        }
        const apiMethod = type.value === 'add' ? addAddress : updateAddress
        if (type.value === 'add') {
          model.id = null
        }
        apiMethod(model).then((res) => {
          uni.showToast({
            title: '提交成功',
            icon: 'none',
          })

          timer = setTimeout(() => {
            uni.$emit('address-list-refresh')
            uni.navigateBack()
          }, 500)
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

const value = ref<string[]>([])
onUnmounted(() => {
  if (timer !== null) {
    clearTimeout(timer)
  }
})
const area = ref<any[]>([])
watch(
  () => value.value,
  () => {
    area.value = [
      colPickerData.map((item) => {
        return {
          value: item.value,
          label: item.text,
        }
      }),
      findChildrenByCode(colPickerData, value.value[0])!.map((item) => {
        return {
          value: item.value,
          label: item.text,
        }
      }),
      findChildrenByCode(colPickerData, value.value[1])!.map((item) => {
        return {
          value: item.value,
          label: item.text,
        }
      }),
    ]
  },
)

const columnChange = ({ selectedItem, resolve, finish }) => {
  const areaData = findChildrenByCode(colPickerData, selectedItem.value)
  if (areaData && areaData.length) {
    resolve(
      areaData.map((item) => {
        // console.log(item)
        return {
          value: item.value,
          label: item.text,
        }
      }),
    )
  } else {
    finish()
  }
}

function handleConfirm({ selectedItems, value }) {
  model.provinceCode = value[0]
  model.cityCode = value[1]
  model.districtCode = value[2]
  model.provinceName = selectedItems[0].label
  model.cityName = selectedItems[1].label
  model.districtName = selectedItems[2].label
  console.log(selectedItems, 'selectedItems')
  model.fullAddress = ''
  selectedItems.forEach((element) => {
    model.fullAddress += element.label
  })
}
const hanleChangeArea = ({ value }) => {
  console.log(value)
}
const id = ref(null)
onMounted(async () => {
  console.log(id)
  if (id.value > 0) {
    const { data, code } = await getAddress(id.value)
    console.log(code, data)

    model.id = data.id
    model.address = data.address
    model.name = data.name
    model.phone = data.phone
    model.isDefault = data.isDefault
    model.tagName = data.tagName
    model.fullAddress = data.fullAddress
    value.value = [data.provinceCode, data.cityCode, data.districtCode]
    model.provinceCode = data.provinceCode
    model.cityCode = data.cityCode
    model.districtCode = data.districtCode
    model.provinceName = data.provinceName
    model.cityName = data.cityName
    model.districtName = data.districtName
  }
})
const type = ref('')
onLoad((options) => {
  console.log(options)
  id.value = options.id
  type.value = options.type
})
</script>

<template>
  <view class="box mt-4">
    <wd-form ref="form" :model="model">
      <wd-cell-group border>
        <wd-input
          label="姓名"
          label-width="100rpx"
          prop="name"
          clearable
          v-model="model.name"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <wd-input
          label="电话"
          label-width="100rpx"
          prop="phone"
          type="number"
          clearable
          v-model="model.phone"
          placeholder="请输入电话"
          :rules="[{ required: true, message: '请填写电话' }]"
        />
      </wd-cell-group>

      <wd-cell-group border class="mt-4">
        <wd-col-picker
          label="选择地址"
          required
          v-model="value"
          auto-complete
          :columns="area"
          :column-change="columnChange"
          @confirm="handleConfirm"
          @change="hanleChangeArea"
        ></wd-col-picker>
        <wd-input
          label="详细地址"
          label-width="200rpx"
          prop="address"
          clearable
          v-model="model.address"
          placeholder="请填写详细地址1-80个字符"
          :rules="[{ required: true, message: '请填写详细地址' }]"
        />
      </wd-cell-group>

      <wd-cell-group border class="mt-4">
        <view
          style="display: flex; align-items: center; justify-content: flex-start; padding: 20rpx 0"
        >
          <text style="margin: 0 30rpx; font-size: 28rpx">地址标签</text>
          <wd-radio-group v-model="model.tagName" shape="button">
            <wd-radio style="color: #ff5f15" value="家">家</wd-radio>
            <wd-radio value="学校">学校</wd-radio>
            <wd-radio value="公司">公司</wd-radio>
          </wd-radio-group>
        </view>

        <wd-cell title="是否设为默认地址">
          <template #default>
            <wd-switch
              active-color="#ff5f15"
              inactive-color="#eee"
              :active-value="1"
              :inactive-value="0"
              label="是否默认地址"
              prop="isDefault"
              v-model="model.isDefault"
            ></wd-switch>
          </template>
        </wd-cell>
      </wd-cell-group>

      <view class="footer">
        <view>
          <wd-button
            style="background: #ff5f15"
            type="primary"
            size="large"
            @click="handleSubmit"
            block
          >
            提交
          </wd-button>
        </view>

        <!-- <view style="margin-top: 30rpx">
          <wd-button type="error" size="large" @click="handleDelete" block>删除</wd-button>
        </view> -->
      </view>
    </wd-form>
  </view>
</template>
<style lang="scss" scoped>
.box {
  background-color: #f8f8f8;
}

.footer {
  padding: 12px;
}
</style>
